<?php
namespace laiq\base;

class View 
{
    protected $variables = [];
    protected $_module;
    protected $_controller;
    protected $_action;

    function __construct($module, $controller, $action) {
        $this->_module = strtolower($module);
        $this->_controller = strtolower($controller);
        $this->_action = strtolower($action);
    }

    // 分配变量
    public function assign($name, $value) {
        $this->variables[$name] = $value;
    }

    // 渲染显示
    public function render() {
        extract($this->variables);
        $defaultHeader = APP_PATH . 'app/views/header.php';
        $defaultFooter = APP_PATH . 'app/views/footer.php';

        $controllerHeader = APP_PATH . 'theme/' . THEME . '/header.php';
        $controllerFooter = APP_PATH . 'theme/' . THEME . '/footer.php';
        $controllerSidebar = APP_PATH . 'theme/' . THEME . '/sidebar.php';
        $controllerLayout = APP_PATH . "app/views/{$this->_module}/{$this->_controller}/{$this->_action}.php";
        
        if (is_file($controllerHeader)) {
            include($controllerHeader);
        } else {
            include($defaultHeader);
        }

        if (is_file($controllerLayout)) {
            include($controllerLayout);
        } else {
            include(APP_PATH . 'theme/' . THEME . '/404.html');
        }
        
        if (is_file($controllerSidebar)) {
            include($controllerSidebar);
        }
        
        if (is_file($controllerFooter)) {
            include($controllerFooter);
        } else {
            include($defaultFooter);
        }
    }
}